//
//  YPhotoView.m
//  TestZoomPhoto
//
//  Created by yull on 14/12/6.
//  Copyright (c) 2014年 yull. All rights reserved.
//

#import "YPhotoView.h"
#import "YPhotoCell.h"
#import "YPhoto.h"
#import <SDWebImageManager.h>
#import "ImageManger.h"

@interface YPhotoView () <UICollectionViewDataSource,UICollectionViewDelegate,YPhotoCellDelegate>

@property (nonatomic, strong) UICollectionView *photoCollectionView;

@property (nonatomic, strong) UIView *blackView;

@property (nonatomic, strong) UIImageView *animatedImageView;

@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UILabel *tipLabel;

@end

@implementation YPhotoView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        self.backgroundColor = [UIColor clearColor];
        
        self.blackView = [[UIView alloc] initWithFrame:self.bounds];
        self.blackView.backgroundColor = [UIColor blackColor];
        [self addSubview:self.blackView];
        
        self.animatedImageView = [[UIImageView alloc] initWithFrame:CGRectZero];
        [self addSubview:self.animatedImageView];
        
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.sectionInset = UIEdgeInsetsZero;
        flowLayout.itemSize = frame.size;
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.minimumLineSpacing = 0;
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
        self.photoCollectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:flowLayout];
        self.photoCollectionView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        self.photoCollectionView.backgroundColor = [UIColor blackColor];
        self.photoCollectionView.dataSource = self;
        self.photoCollectionView.delegate = self;
        self.photoCollectionView.pagingEnabled = YES;
        [self addSubview:self.photoCollectionView];
        
        [self.photoCollectionView registerClass:[YPhotoCell class] forCellWithReuseIdentifier:@"PhotoCell"];
        
        CGRect rect = CGRectMake(10, self.height - 44, self.width - 20, 44);
        self.bottomView = [[UIView alloc] initWithFrame:rect];
        self.bottomView.backgroundColor = [UIColor clearColor];
        [self addSubview:self.bottomView];
        
        self.tipLabel = [[UILabel alloc] initWithFrame:self.bottomView.bounds];
        self.tipLabel.textAlignment = NSTextAlignmentCenter;
        self.tipLabel.textColor = [UIColor grayColor];
        self.tipLabel.font = [UIFont systemFontOfSize:18.0f];
        self.tipLabel.userInteractionEnabled = YES;
        [self.bottomView addSubview:self.tipLabel];
        
        UIButton *downButton = [UIButton buttonWithType:UIButtonTypeCustom];
        downButton.frame = CGRectMake(self.bottomView.width - 40, 7, 40, 30);
        [downButton setImage:[UIImage imageNamed:@"save_image_icon"] forState:UIControlStateNormal];
        [downButton setImage:nil forState:UIControlStateHighlighted];
        downButton.imageEdgeInsets = UIEdgeInsetsMake(5, 12, 5, 12);
        [self.bottomView addSubview:downButton];
        [downButton addTarget:self action:@selector(downImage:) forControlEvents:UIControlEventTouchUpInside];
    }
    return self;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.photoArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    YPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PhotoCell" forIndexPath:indexPath];
    cell.delegate = self;
    
    YPhoto *photo = [self.photoArray objectAtIndex:indexPath.row];
    [cell drawCellWithPhoto:photo];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    self.showIndex = indexPath.row;
    
    YPhotoCell *cell = (YPhotoCell *)[collectionView cellForItemAtIndexPath:indexPath];
    
    UIImage *image;
    CGRect rect;
    if (cell.imageView.image) {
        image = cell.imageView.image;
        rect = [self convertRect:cell.imageView.frame fromView:cell.contentView];
    }else if (cell.thumbImageView.image){
        image = cell.thumbImageView.image;
        rect = [self convertRect:cell.thumbImageView.frame fromView:cell.contentView];
    }
    
    [self hidePhotoViewFromRect:rect image:image];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSArray *visibleIndexPath = [self.photoCollectionView indexPathsForVisibleItems];
    
    NSInteger index = 0;
    
    for (NSIndexPath *path in visibleIndexPath){
        index = MAX(path.row, index);
    }
    
    self.showIndex = index;
}

- (void)setPhotoArray:(NSArray *)photoArray
{
    _photoArray = photoArray;
    
    [self.photoCollectionView reloadData];
}

- (void)setShowIndex:(NSInteger)showIndex
{
    _showIndex = showIndex;
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:showIndex inSection:0];
    
    [self.photoCollectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    
    self.tipLabel.text = [NSString stringWithFormat:@"%d/%d",self.showIndex+1,self.photoArray.count];
    
    CGSize size = [self.tipLabel sizeThatFits:CGSizeZero];
    self.tipLabel.width = size.width;
}

- (void)showPhotoViewWithImage:(UIImage *)image
{
    YPhoto *photo = [self.photoArray objectAtIndex:self.showIndex];
    self.animatedImageView.frame = photo.imageRect;
    
    CGSize imageSize;
    if (photo.image) {
        self.animatedImageView.image = photo.image;
        imageSize = [YPhoto getImageSize:photo.image];
    }else {
        if (photo.hasBig) {
            UIImage *bigImage = [ImageManger SDWebImageForUrl:photo.imageUrl];
            imageSize = [YPhoto getImageSize:bigImage];
            self.animatedImageView.image = bigImage;
        }else {
            self.animatedImageView.image = photo.thumbImage;
            imageSize = [YPhoto getImageSize:photo.thumbImage];
        }
        
    }
    
    CGRect endRect = CGRectMake(self.width/2-imageSize.width/2, self.height/2-imageSize.height/2, imageSize.width, imageSize.height);
    self.hidden = NO;
    self.alpha = 1.0f;
    self.blackView.alpha = 0.0f;
    self.bottomView.alpha = 0.0f;
    self.animatedImageView.hidden = NO;
    self.photoCollectionView.hidden = YES;
    
    [UIView animateWithDuration:0.5f delay:0.0f options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.animatedImageView.frame = endRect;
        self.blackView.alpha = 1.0f;
        self.bottomView.alpha = 1.0f;
    } completion:^(BOOL finished) {
        if (finished) {
            self.animatedImageView.hidden = YES;
            self.photoCollectionView.hidden = NO;
        }
    }];
}

- (void)hidePhotoViewFromRect:(CGRect)rect image:(UIImage *)image
{
    YPhoto *photo = [self.photoArray objectAtIndex:self.showIndex];
    
    self.animatedImageView.frame = rect;
    self.animatedImageView.image = image;
    
    self.blackView.alpha = 1.0f;
    self.bottomView.alpha = 1.0f;
    self.animatedImageView.hidden = NO;
    
    self.photoCollectionView.hidden = YES;
    
    [UIView animateWithDuration:0.5f delay:0.0f options:UIViewAnimationOptionCurveEaseInOut animations:^{
        if (!CGRectEqualToRect(photo.imageRect, CGRectZero)) {
            self.animatedImageView.frame = photo.imageRect;
            self.blackView.alpha = 0.0f;
            self.bottomView.alpha = 0.0f;
        }else {
            self.alpha = 0.0f;
        }
    } completion:^(BOOL finished) {
        if (finished) {
            self.animatedImageView.hidden = YES;
            self.hidden = YES;
            
            if ([self.delegate respondsToSelector:@selector(photoViewHide)]) {
                [self.delegate photoViewHide];
            }
        }
    }];
}

- (void)onTapPhotoAtCell:(YPhotoCell *)cell
{
    UIImage *image;
    CGRect rect;
    if (cell.imageView.image) {
        image = cell.imageView.image;
        rect = [self convertRect:cell.imageView.frame fromView:cell.contentView];
    }else if (cell.thumbImageView.image){
        image = cell.thumbImageView.image;
        rect = [self convertRect:cell.thumbImageView.frame fromView:cell.contentView];
    }
    
    [self hidePhotoViewFromRect:rect image:image];
}

- (void)downImage:(id)sender
{
    YPhotoCell *cell = [self.photoCollectionView visibleCells].firstObject;
    
    if (cell.imageView.image) {
        [self saveImageToPhotos:cell.imageView.image];
    }else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"图片下载未完成!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }
}

- (void)saveImageToPhotos:(UIImage*)savedImage
{
    UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}

- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
{
    NSString *msg = nil ;
    if(error != NULL){
        msg = @"保存图片失败" ;
    }else{
        msg = @"保存图片成功" ;
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert show];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    NSLog(@"touch ");
}
@end
